package com.block.product.service.union;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.http.HttpUtil;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.service.LogFactory;
import com.block.product.model.dto.UniLoginDTO;
import com.block.product.model.param.ProdApiInfoParam;
import com.block.product.model.result.UnionLoginResult;
import com.block.product.service.IUnionLoginService;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
public class WeiJieHuaUnionLoginService implements IUnionLoginService {

    private static final Logger log = LogFactory.getProductUniLog();

    @Override
    public UnionLoginResult checkUser(UniLoginDTO uniLoginDTO, ProdApiInfoParam apiInfoParam) {
        UnionLoginResult loginResult = new UnionLoginResult();
        loginResult.setSuccess(true);
        return loginResult;
    }

    @Override
    public UnionLoginResult loginUser(UniLoginDTO uniLoginDTO, ProdApiInfoParam apiInfoParam,String resultInfo) {

        UnionLoginResult loginResult = new UnionLoginResult();
        loginResult.setSuccess(false);

        String checkUrl = apiInfoParam.getLoginUrl();
        String mobile = uniLoginDTO.getMobile();


        Map<String, Object> bizmMap = new HashMap<>();
        bizmMap.put("phone", mobile);
        bizmMap.put("ip", uniLoginDTO.getReqIp());
        bizmMap.put("channelCode", apiInfoParam.getApiCode());

        String sign = encrypt(JSON.toJSONString(bizmMap), apiInfoParam.getApiSecret());

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("sign", sign);



        log.info("【微借花】联登开始【queryUrl】{}【paramMap】{}", checkUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(checkUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【微借花】联登结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String message = resultObject.getString("msg");

        loginResult.setCode(String.valueOf(code));
        loginResult.setMessage(message);
        loginResult.setResultInfo(result);
        loginResult.setParamInfo(JSON.toJSONString(paramMap));

        if (StrUtil.equals(String.valueOf(code), "200")) {
            JSONObject data = resultObject.getJSONObject("data");
            Integer status = data.getInteger("status");
            if (StrUtil.equals(String.valueOf(status), "1")) {
                String url = data.getString("downUrl");
                loginResult.setSuccess(true);
                loginResult.setLoginUrl(url);
            }
        }
        return loginResult;
    }


    public static String encrypt(String contentStr, String key) {
        try {
            if(StringUtils.isEmpty(contentStr)) {
                return null;
            }
            byte[] raw = key.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(contentStr.getBytes(StandardCharsets.UTF_8));
            return new org.apache.commons.codec.binary.Base64().encodeToString(encrypted);
        } catch(Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
